#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: lijk34925
   @Time: 2025/4/14 15:46
   @File: risk_review_index_task.py
   @desc: 调度执行调度任务
"""
import json
import time

from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.utils.variable import Variable

from BladeFerm.hui12_common.function import display_wait
from BladeFerm.hui2_app import FE
from BladeFerm.Lib.Common import logger
from BladeFerm.databases import DB_APP
from HGScripts.common_test_prepare import common_test_prepare, open_scene_detail, open_menu_nk
from CommonScripts.check_result_hui_two import common_assert_except
from CommonScripts.index_rule_cal import indexJobAction


bladeVer = Variable()


@common_test_prepare
def run_rule_task(input_data=None, ui_expect=None):
    '''
    子项调度任务执行、断言、修改页面参数
    input_data 入参：
        指标编号： risk_id
        vd： occur_date
    '''
    # STEP1:装饰器内执行数据预埋
    env = bladeVer.get_variable('varg_db_type')
    rule_no = input_data.get('指标编号', 'none')
    test_date = input_data.get('发生日期', '20240321')
    logger.info(f'任务标号为: {rule_no}')
    if rule_no:  # 通过入参为任务编号来执行调度任务和用户得分断言
        # blade_rule_no = bladeVer.get_variable("varg_blade_rule_no")
        run_task_flag = True
        # if blade_rule_no and blade_rule_no == rule_no:
        #     # STEP2: 判断是否修改参数并刷新过缓存？刷新缓存了，则需要重新执行规则任务
        #     refresh_cache_server = bladeVer.get_variable("varg_refresh_cache_flag")
        #     if refresh_cache_server and 'TRUE' == refresh_cache_server:
        #         run_task_flag = True
        #         bladeVer.set_variable("varg_refresh_cache_flag", "FALSE")
        #     else:
        #         run_task_flag = False
        #         logger.info(f'任务编号{rule_no}已经执行，跳过直接断言！')
        if run_task_flag:
            # 删除结果表数据
            sql_del = f"DELETE FROM hsrcce.RCCE_R_MONITOR_RESULT WHERE risk_id='{rule_no}';"
            DB_APP.run_one_sql(sql_del)
            # 执行任务
            bladeVer.set_variable("varg_blade_rule_no", rule_no)  # 更新任务编号
            task_params = {
                "risk_id": {"name": "risk_id", "value": rule_no, "custom": True, "direct": "", "index": 0},
                "occur_date": {"name": "occur_date", "value": test_date, "custom": True, "direct": "", "index": 2}
            }
            input_data_params = {'jobName': f'prod_bu_smt_risk_ta_{rule_no}',
                                 'jobGroup': 'default',
                                 'taskParam': json.dumps(task_params),
                                 'env': env,
                                 'project': 'HG5'}
            indexJobAction(input_data=input_data_params, ui_expect={'flag': True})
        # STEP3:断言
        ui_expect.update({'risk_id': input_data.get('指标编号', '000000')})
        _check_rule_result(ui_expect=ui_expect)
    else:
        raise SeleniumError(f"入参错误，没有 `规则编号`！")


def _check_rule_result(ui_expect=None):
    """
    查看可疑规则预警结果
    :param ui_expect:
        risk_id: 规则编号
        AI生成用例的格式：risk_level=[{"等级":3,"条件":{"client_id":"10002"}},{"等级":5,"条件":{"client_id":"10003"}}]
        手工公里书写格式： risk_level=0/3/5 等
    :param env:
    :return:
    """
    def __check_risk_level(sql, expect):
        result_list = DB_APP.run_one_sql(sql)
        if result_list:
            common_assert_except(result_list, expect)
            return True
        else:
            error = f'SQL {sql} 查询为空，无法继续断言请检查！'
            logger.error(error)
            raise SeleniumError(error)
    risk_id = ui_expect.pop('risk_id', '000000')
    risk_level = ui_expect.pop('risk_level', None)
    sql_query = f"SELECT RISK_LEVEL FROM hsrcce.RCCE_R_MONITOR_RESULT WHERE risk_id='{risk_id}'"
    if risk_level and risk_level.startswith('[') and risk_level.endswith(']'):
        risk_level_list = json.loads(risk_level)
        for risk_level_item in risk_level_list:
            condition_dict = risk_level_item.get('条件', {})
            risk_level_number = risk_level_item.get('等级', -1)
            temp_where = ""
            for k, v in condition_dict.items():
                temp_where += f" and {k}='{v}'"
            sql_query_temp = sql_query + temp_where
            expect_dict = {'risk_level': risk_level_number}
            __check_risk_level(sql_query_temp, expect_dict)
    else:
        expect_dict = {'risk_level': risk_level}
        __check_risk_level(sql_query, expect_dict)


@common_test_prepare
def check_rule_result(input_data=None, ui_expect=None):
    """
    查看指标的场景详情，预警明细，
    DELETE  FROM hssrmps.srmps_scene_occur t  WHERE  t.SCENE_NO ='1101008' AND t.CLIENT_ID ='111';
    DELETE FROM hssrmps.srmps_H_scene_occur t  WHERE  t.SCENE_NO ='1101008'  ;

    SELECT  * FROM  hsrcce.RCCE_SCENE r WHERE  r.SCENE_NO ='1101008'  ;
    :param input_data:
    :param ui_expect:
    :return:
    """
    # 步骤1：打开菜单
    input_data_menu = {'菜单名称': '监控中心-监控中心首页'}
    open_menu_nk(input_data_menu)
    # 步骤2：打开目标场景
    risk_name = input_data.get('场景名称', None)
    if not risk_name:
        err_1 = f"入参错误，没有 `场景名称`！"
        logger.error(err_1)
        raise SeleniumError(err_1)
    open_scene_detail(risk_name)
    time.sleep(0.5)
    # 步骤3：打开场景对应的预警明显。默认打开第一条。（场景触发测试前，需要删除历史记录，确保此处打开的是新触发的场景）
    xpath_form = '//form[contains(@class,"rcmp-st-search-form")]'
    scene_form = FE.form(idname={'xpath': xpath_form})
    scene_form.button_option('重置')
    scene_form.auto_fill_group(input_data)
    scene_form.button_option('查询')
    scene_table_1 = FE.table_new(idname={'xpath': '(//div[@class="h-datagrid"])[1]//div[@class="h-table-box"]//table'})
    scene_table_1.click_row_by_ids('2')
    # 步骤4：点击预警明细的第一条，断言预警明细信息
    res = display_wait(idname={'xpath': '(//div[@class="h-datagrid"])[2]//div[@class="h-table-body"]/table/tbody/tr'},
                       flag=1, timeout=5, driver=FE.driver)
    if res:
        scene_table_2 = FE.table_new(idname={'xpath': '(//div[@class="h-datagrid"])[2]//table'})
        scene_table_2.checkData(ui_expect)
    else:
        raise SeleniumError(f"未查询到预警明细，请检查！")


def check_rule_reason(input_data=None, ui_expect=None):
    """
    查看指标的场景详情，触发原因 断言
    :param input_data:
    :param ui_expect:
    :return:
    """
    # 步骤1：点击预警明细的第一条，打开触发原因和预警流水
    scene_table = FE.table_new(idname={'xpath': '(//div[@class="h-datagrid"])[2]//table'})
    scene_table.click_row_by_ids(1)
    time.sleep(0.5)
    # 步骤2：断言触发原因
    drawer_table_xpath = '//div[contains(@class,"h-drawer-content")]//div[@class="h-table-box"]//table'
    reason_table = FE.table_new({'xpath': drawer_table_xpath}, father=FE.driver)
    reason_table.checkData(ui_expect)
    # 步骤3: 关闭弹框
    scene_table.click_row_by_ids(1)


def check_rule_flow_detail(input_data=None, ui_expect=None):
    """
    查看指标的场景详情，预警流水 断言
    :param input_data:
    :param ui_expect:
    :return:
    """
    # 步骤1：点击预警明细的第一条，打开触发原因和预警流水
    scene_table = FE.table_new(idname={'xpath': '(//div[@class="h-datagrid"])[2]//table'})
    scene_table.click_row_by_ids(1)
    time.sleep(0.5)
    # 步骤2：切换到预警流水
    risk_tab_xpath = '//div[contains(@class,"h-drawer-content")]//div[@class="h-tabs-nav"]/div[contains(text(),"预警流水")]'
    tab_ele = FE.driver.find_element_by_xpath(risk_tab_xpath)
    tab_ele.click()
    time.sleep(0.5)
    # 步骤3：断言预警流水
    drawer_table_xpath = '//div[contains(@class,"h-drawer-content")]//div[@class="h-table-box"]//table'
    reason_table = FE.table_new({'xpath': drawer_table_xpath}, father=FE.driver)
    reason_table.checkData(ui_expect)
    # 步骤4: 关闭弹框
    scene_table.click_row_by_ids(1)